package com.ncucoder.server.producer;

import com.alibaba.fastjson.JSON;
import com.ncucoder.server.constant.MessageConstants;
import com.ncucoder.server.model.Message;
import com.ncucoder.server.model.Order;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;

/**
 * @author <a href="https://www.ncucoder.com">hsowan</a>
 * @since 2019-01-19 20:48
 */
@Component
public class OrderProducer {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void sendMessage(Order order){

        Long time = System.currentTimeMillis();
        Timestamp createAndUpdateTime = new Timestamp(time);
        Timestamp nextRetry = new Timestamp(time + 60000 * MessageConstants.INTERVAL);

        Message message = new Message(JSON.toJSONString(order), MessageConstants.SENDING, 0, nextRetry, createAndUpdateTime, createAndUpdateTime);

        rabbitTemplate.setConfirmCallback((correlationData, b, s) -> {
            if (b){
                System.out.println("ack");
            }else {
                System.out.println("nack");
            }
        });
        CorrelationData correlationData = new CorrelationData();
        rabbitTemplate.convertAndSend("order-exchange", "order.secKill", JSON.toJSONString(message), correlationData);
    }
}
